import axios from 'axios'

// 创建axios实例
const absentApi = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8181',
  timeout: 10000
})

// 获取缺寝列表
export const getAbsentList = (page, size) => {
  return absentApi.get(`/absent/list/${page}/${size}`)
    .then(response => {
      // 根据你的后端数据结构调整
      return {
        data: response.data.data.data, // 实际数据
        total: response.data.data.total // 总条数
      }
    })
    .catch(error => {
      console.error('获取缺寝列表失败:', error)
      throw error
    })
}

// 搜索缺寝记录
export const searchAbsent = (params) => {
  return absentApi.get('/absent/search', { params })
    .then(response => {
      return {
        data: response.data.data.data,
        total: response.data.data.total
      }
    })
    .catch(error => {
      console.error('搜索缺寝记录失败:', error)
      throw error
    })
}
export const getBuildingList = async () => {
  try {
    const response = await absentApi.get('/absent/buildingList')
    return {
      code: 0,
      data: response.data.data
    }
  } catch (error) {
    console.error('获取楼宇列表失败:', error)
    throw error
  }
}

// 根据楼宇获取宿舍
export const getDormitoryByBuilding = async (buildingId) => {
  try {
    const response = await absentApi.get(`/absent/findDormitoryByBuildingId/${buildingId}`)
    return {
      code: 0,
      data: response.data.data
    }
  } catch (error) {
    console.error('获取宿舍列表失败:', error)
    throw error
  }
}

// 根据宿舍获取学生
export const getStudentByDormitory = async (dormitoryId) => {
  try {
    const response = await absentApi.get(`/absent/findStudentByDormitoryId/${dormitoryId}`)
    return {
      code: 0,
      data: response.data.data
    }
  } catch (error) {
    console.error('获取学生列表失败:', error)
    throw error
  }
}

// 保存缺寝记录
export const saveAbsentRecord = async (data) => {
  try {
    const response = await absentApi.post('/absent/save', data)
    return response.data
  } catch (error) {
    console.error('保存缺寝记录失败:', error)
    throw error
  }
}